﻿using Microsoft.Extensions.Hosting;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.Common.LogHelper;
using MyCompany.MyProject.Serilog.Configuration;
using MyCompany.MyProject.Serilog.Extensions;
using Serilog;
using Serilog.Debugging;
using Serilog.Sinks.SystemConsole.Themes;
using System.Net;

namespace MyCompany.MyProject.Extensions.ServiceExtensions;

public static class SerilogSetup
{
    /// <summary>
    /// 添加 Serilog 功能
    /// </summary>
    /// <param name="builder"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static IHostBuilder AddSerilogSetup(this IHostBuilder builder)
    {
        if(builder == null) throw new ArgumentNullException(nameof(builder));

        var loggerConfiguration = new LoggerConfiguration()
            .ReadFrom.Configuration(AppSettings.Configuration)
            .Enrich.FromLogContext()
            //.WriteToConsole()
            //.WriteTo.Console(theme: AnsiConsoleTheme.Code)
            .WriteToFile()
            //.WriteTo.Email(new EmailConnectionInfo()
            //{
            //    EmailSubject = "系统警告,请速速查看!",//邮件标题
            //    FromEmail = "291***@qq.com",//发件人邮箱
            //    MailServer = "smtp.qq.com",//smtp服务器地址
            //    NetworkCredentials = new NetworkCredential("291***@qq.com", "###########"),//两个参数分别是发件人邮箱与客户端授权码
            //    Port = 587,//端口号
            //    ToEmail = "183***@163.com"//收件人
            //})
            .WriteToLogBatching();

        Log.Logger = loggerConfiguration.CreateLogger();

        // Serilog 内部日志
        var file = File.CreateText(LogContextStatic.Combine($"SerilogDebug{DateTime.Now:yyyyMMdd}.txt"));
        SelfLog.Enable(TextWriter.Synchronized(file));

        builder.UseSerilog();
        return builder;
    }
}
